#include "data_refresh.h"
data_refresh dat;


u8 sleep_flg ;//菜单选择是否低功耗
u8 fail_count ;
u8 low_power_flg ;
s8 love_y;
u8 love_mode;

u8 data_refresh::conect_wifi()
{
    if(WiFi.status() == WL_CONNECTED)
    {
        return 1;
    }
    else
    {
        WiFi.forceSleepWake();
        if(wifima.conect_last())
        {
            low_power_flg = 0;
            return 1;
        }
        else
        {
            low_power_flg = 1;
            return 0;
        }
            
    }
}

void data_refresh::low_power_set()
{
    if(low_power_flg||sleep_flg)
    {
        WiFi.disconnect();
        WiFi.mode(WIFI_OFF);
        WiFi.forceSleepBegin();    
    }    
}

void data_refresh::refre_weather(u8 mode)
{
    s8 x = -15;

    rssi_flg = 0;
    
    if( mode)
    {
        ui.show_icon_out();
        ui.data_refresh_move_out();
    }
    ui.set_cpu_freq(HIGH_FREQ);
    oled.xy_set(0,0,128,8);
    while(x<0)
    {
        oled.choose_clr(56,0,15,8);
        oled.BMP(56,x++,15,15,love,1);
        oled.choose_refresh(56,0,15,8);
        yield();
    }
    love_y = 0;
    love_mode = 1;
    wea_updata_tic.attach_ms(16,wea_updata);
    x = weather();
    low_power_set();
    if(!x)
    {
        if(fail_count<4)
            fail_count++;
        if(fail_count ==3)
        {
            hweather.icon = 0;
            hweather.weather = "";
            hweather.wind = "";  
        } 
    }
    else
    {

        fail_count = 0;
    }
    while(love_y<49)
    {
        yield();
    }
    wea_updata_tic.detach();
    while(love_y<65)
    {
        oled.choose_clr(56,0,15,8);
        oled.BMP(56,love_y++,15,15,love,1);
        oled.choose_refresh(56,0,15,8);
        yield();
    }
    ui.data_refresh_move_in();
    ui.show_icon_in();
    rssi_flg = 1;
}



u8 data_refresh::weather()
{
    if(conect_wifi())    
    {
        if(hweather.locationID != "0")
        {
            if(hweather.get_weather(hweather.locationID))
            {
                hweather.get_future_weather(hweather.locationID);
                return 1;
            }
            else
            {
                return 0;
            }
        }
        else
        {
            if(setwifi.get_location())
            {
                if(hweather.get_city(location_text_buf))
                {
                    weather();
                }
                else
                {
                    return 0;
                }
            }    
        }
    }
    else
    {
        return 0;
    }

}

void data_refresh::refre_time()
{
    if(conect_wifi())    
    {
        if(ntime.get())
        {
            pcf.write_day(ntime.year,ntime.month,ntime.day,ntime.week);
            pcf.write_time(ntime.hour,ntime.min,ntime.second);
        }
    }
    low_power_set();
}



